// pages/deviceDetail/deviceDetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 1, //1 基本信息 2 配置信息 3 app限制
    showDialog: false,
    baseInfoOpen: true,
    customInfoOpen: true,
    historyInfoOpen: true,
    id: 0,
    detailInfo: null,
    deviceInfo: null,
    activationLockStatus: 0,
    items: [],
    page: 1,
    pageSize: 10,
    isLoading: false,
    noMoreData: false,
    isRefreshing: false,
    showOperaDialog: false,
    showEditDialog: false,
    showLoseDialog: false,
    type: 0, //菜单按钮类型
    operaTitle: '提示',
    option: [{
        text: '闲置',
        value: 0
      },
      {
        text: '租出',
        value: 1
      },
    ],

    scrollyHeight: wx.getSystemInfoSync().windowHeight,

    newEditName: '', //设备名称
    newEditState: '', //设备状态
    newEditAdmin: '', //设备持有者
    newEditIdCard: '', //设备持有者身份证
    newEditPhone: '', //设备持有者手机号  
    newAssertNumber: '', //资产编号  
    newPurchaseTime: '', //采购日期
    newWarrantyTime: '', //维保到期日期 
    newRemark: '', //备注
    lostPhone: '',
    lostContent: '',


    shopPage: 1,
    shopPageSize: 10,
    isLoadingShop: false,
    noMoreDataShop: false,
    isRefreshingShop: false,
    shopItems: [],
    showShopDialog: false,
    selectShop: null,

    enterpPage: 1,
    enterpPageSize: 10,
    isLoadingEnterp: false,
    noMoreDataEnterp: false,
    isRefreshingEnterp: false,
    enterpItems: [],
    selectEnterp: null,
    showEnterpriseDialog: false,

    showPayDialog: false,
    showCodeDialog: false,
    code: '',
    showAppDialog: false,
    rentIdentifierOptions: null,
    rentIdentifierVaule: 0,
    appList: null,
    restrictItems: null,
    actionList: [],
    merchantMdmPrice: 20,

    showSceondPasswordDialog: false,
    secondPassword: ''
  },

  selectTab: function (e) {
    let tab = e.currentTarget.dataset.tab
    let {
      detailInfo
    } = this.data
    if (tab == 2) {
      this.getDeviceConfig()
    }
    if (tab == 3) {
      if (detailInfo.deviceStatus == 4) {
        this.queryAppListById(detailInfo.rentIdentifierId)
      } else if (detailInfo.deviceStatus == -1) {
        wx.showToast({
          title: '收租指令正在下发中，请耐心等候',
          icon: 'none',
          duration: 3000
        })
        return
      } else {
        wx.showToast({
          title: '该设备不是收租模式',
          icon: 'none',
          duration: 3000
        })
        return
      }
    }
    if (tab == 4) {
      this.queryAllFunctionRestrict()
    }
    this.setData({
      currentTab: tab
    })
  },

  getDeviceConfig: function () {
    let that = this
    let params = {
      id: this.data.id
    }
    getApp().api.getDeviceConfig(params, {
      success: function (res) {
        that.setData({
          restrictItems: res.data.restrictItem
        })
      },
      fail: function (err) {

      }
    });
  },

  /**
   * 获取功能配置
   */
  queryAllFunctionRestrict: function () {
    let that = this
    let params = {
      deviceId: this.data.id
    }
    getApp().api.queryAllFunctionRestrict(params, {
      success: function (res) {
        let actionList = res.data
        actionList.forEach(v => {
          if (v.nowValue == "true") {
            v.nowValue = true
          } else {
            v.nowValue = false
          }
        })
        that.setData({
          actionList: res.data
        })
      },
      fail: function (err) {

      }
    });
  },

  /**
   * 下发配置
   */
  setFunctionRestrict: function () {
    const {
      id,
      actionList
    } = this.data
    let params = {
      id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }

    let functionRestrictData = {}
    actionList.forEach(v => {
      let restrictKey = v.restrictKey
      functionRestrictData[restrictKey] = v.nowValue + ""
    })
    params.functionRestrictData = JSON.stringify(functionRestrictData)
    wx.showLoading({
      title: '配置下发中',
    })
    getApp().api.setFunctionRestrict(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '下发成功',
          icon: 'none'
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '下发失败：' + (err.message || ''),
          icon: 'none'
        })
      }
    })
  },

  /**
   * 设置信
   */
  setInfo: function () {
    let {
      detailInfo,
      deviceInfo
    } = this.data

    this.setData({
      newEditName: detailInfo.name, //设备名称
      newEditState: detailInfo.useStatus, //设备状态
      newEditAdmin: detailInfo.possessor, //设备持有者
      newEditIdCard: detailInfo.possessorCard, //设备持有者身份证
      newEditPhone: detailInfo.mobilePhone, //设备持有者手机号    
      newAssertNumber: detailInfo.assetNumber, //设备资产编号  
      newRemark: detailInfo.remark, //备注
      newPurchaseTime: detailInfo.purchaseTimeValue == null || detailInfo.purchaseTimeValue == '' ? '' : getApp().util.formatTime7(detailInfo.purchaseTimeValue), //采购日期
      newWarrantyTime: detailInfo.warrantyTimeValue == null || detailInfo.warrantyTimeValue == '' ? '' : getApp().util.formatTime7(detailInfo.warrantyTimeValue), //维保到期日期
    })
  },

  /**
   * 输入框
   */
  inputPopInfo: function (e) {
    let type = e.currentTarget.dataset.type
    let value = e.detail.value
    switch (type) {
      case 'name':
        this.setData({
          newEditName: value
        })
        break;

      case 'admin':
        this.setData({
          newEditAdmin: value
        })
        break;

      case 'idCard':
        this.setData({
          newEditIdCard: value
        })
        break;

      case 'phone':
        this.setData({
          newEditPhone: value
        })
        break;

      case 'assert':
        this.setData({
          newAssertNumber: value
        })
        break

      case 'remark':
        this.setData({
          newRemark: value
        })
        break

      case 'losephone':
        this.setData({
          lostPhone: value
        })
        break

      case 'losecontent':
        this.setData({
          lostContent: value
        })
        break

      case 'secondPassword':
        this.setData({
          secondPassword: value
        })
        break
    }
  },

  /**
   * 编辑提交
   */
  confirmEdit: function () {
    let that = this
    let {
      id,
      newEditName,
      newEditState,
      newEditAdmin,
      newEditIdCard,
      newEditPhone,
      newAssertNumber,
      newRemark,
      newPurchaseTime,
      newWarrantyTime,
      detailInfo
    } = this.data

    if (newEditName == '') {
      wx.showToast({
        title: '请输入设备名称',
        icon: 'none'
      })
      return
    }

    if (newEditAdmin == '') {
      wx.showToast({
        title: '请输入持有者姓名',
        icon: 'none'
      })
      return
    }
    if (newEditIdCard != '' && newEditIdCard != null) {
      const idRegExp = /^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/;
      if (!idRegExp.test(newEditIdCard)) {
        wx.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        })
        return
      }
    }
    if (newEditPhone != '' && newEditPhone != null) {
      const phoneRegExp = /^1[3-9]\d{9}$/;
      if (!phoneRegExp.test(newEditPhone)) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
    }


    wx.showLoading({
      title: '编辑中',
    })
    let params = {
      id: id,
      name: newEditName,
      serialNumber: detailInfo.serialNumber,
      useStatus: newEditState,
      possessor: newEditAdmin,
    }
    if (newEditPhone) {
      params.mobilePhone = newEditPhone
    }
    if (newEditIdCard) {
      params.possessorCard = newEditIdCard
    }
    if (newAssertNumber) {
      params.assetNumber = newAssertNumber
    }
    if (newRemark) {
      params.remark = newRemark
    }
    if (newPurchaseTime) {
      params.purchaseTimeValue = new Date(newPurchaseTime).getTime()
    }
    if (newWarrantyTime) {
      params.warrantyTimeValue = new Date(newWarrantyTime).getTime()
    }

    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    console.log(params)
    getApp().api.deviceEdit(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '编辑成功',
          icon: 'none'
        })
        that.setData({
          showEditDialog: false
        })
        that.getMyDeviceById()
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '编辑失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },


  baseOpen: function () {

    this.setData({
      baseInfoOpen: !this.data.baseInfoOpen
    })
  },

  customOpen: function () {

    this.setData({
      customInfoOpen: !this.data.customInfoOpen
    })
  },


  historyOpen: function () {

    this.setData({
      historyInfoOpen: !this.data.historyInfoOpen
    })
  },

  showDialog: function () {
    this.setData({
      showDialog: true
    })
  },
  cancle: function () {
    this.setData({
      showDialog: false,
      showShopDialog: false,
      showEnterpriseDialog: false
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let id = options.id
    let activationLockStatus = options.state
    this.setData({
      id,
      activationLockStatus,
      scrollyHeight: getApp().px2rpx(wx.getSystemInfoSync().windowHeight) - 152
    })
    wx.showLoading({
      title: '加载中...',
    })
    this.getMyDeviceById()
    this.getMyDeviceInfoById()
    this.getDeviceOperationLogList()
    this.rentIdentifierQueryAll()

    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      this.setData({
        merchantMdmPrice: getApp().globalData.MerchantStoreInfo.lockupPrice / 100
      })
    } else {
      this.getMerchantMdmPrice()
    }
  },

  /**
   * 获取设备详情
   */
  getMyDeviceById: function (refresh = false) {
    let that = this
    let params = {
      id: this.data.id,
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.getMyDeviceById(params, {
      success: function (res) {
        if (res.data) {
          let detailInfo = res.data
          that.setData({
            detailInfo
          })
          that.setInfo()
          wx.hideLoading()
        }
      },
      fail: function (err) {
        wx.hideLoading()
      }
    });
  },

  getMyDeviceByIdCallback: function (callback) {
    let that = this
    let params = {
      id: this.data.id,
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.getMyDeviceById(params, {
      success: function (res) {
        if (res.data) {
          let detailInfo = res.data
          that.setData({
            detailInfo
          })
          that.setInfo()
          wx.hideLoading()
        }
        if (callback) {
          callback.finish()
        }
      },
      fail: function (err) {
        wx.hideLoading()
        if (callback) {
          callback.finish()
        }
      }
    });
  },
  /**
   * 获取设备硬件详情
   */
  getMyDeviceInfoById: function (refresh = false) {
    let that = this
    let params = {
      deviceId: this.data.id,
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.getMyDeviceInfoById(params, {
      success: function (res) {
        if (res.data) {
          let deviceInfo = res.data
          that.setData({
            deviceInfo
          })
          wx.hideLoading()
        }
      },
      fail: function (err) {
        wx.hideLoading()
      }
    });
  },



  /**
   * 获取操作记录
   */
  getDeviceOperationLogList: function (refresh = false) {
    var that = this;
    if (this.data.isLoading) return;
    this.setData({
      isLoading: true
    });
    const {
      id,
      page,
      pageSize
    } = this.data;
    if (!refresh) {
      wx.showLoading({
        title: '加载中',
      })
    }
    let params = {
      deviceId: id,
      page: page,
      limit: pageSize
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.getDeviceOperationLogList(params, {
      success: function (res) {
        if (res.data.rows) {
          let items = res.data.rows
          items = refresh ? items : that.data.items.concat(items),
            items.forEach(e => {
              e.formatTime = getApp().util.formatTime8(e.createTimeValue)
            })
          that.setData({
            items: items,
            noMoreData: res.data.total > items.length ? false : true,
            isRefreshing: false,
            isLoading: false
          })
          wx.hideLoading()
        }
      },
      fail: function (err) {
        that.setData({
          isRefreshing: false,
          isLoading: false
        });
        wx.hideLoading()
      }
    });
  },



  /**
   * 获取配置列表
   */
  rentIdentifierQueryAll: function () {
    var that = this;
    let params = {

    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.rentIdentifierQueryAll(params, {
      success: function (res) {
        let result = res.data
        let items = [result.length]
        result.forEach((e, i) => {
          let item = {
            'text': e.identifierName,
            'value': e.id,
          }
          items[i] = item
        })
        that.setData({
          rentIdentifierOptions: items
        })
        if (result && result.length > 0) {
          that.queryAppListById(result[0].id)
        }
      },
      fail: function (err) {}
    });
  },


  /**
   * 获取配置列表
   */
  getMerchantMdmPrice: function () {
    var that = this;
    let params = {

    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.getMerchantMdmPrice(params, {
      success: function (res) {
        let result = res.data / 100
        console.log(result)
        that.setData({
          merchantMdmPrice: result
        })
      },
      fail: function (err) {}
    });
  },







  /**
   * 获取配置APP列表
   */
  queryAppListById: function (id) {
    var that = this;
    let params = {
      id
    }
    wx.showLoading({
      title: '加载中',
    })
    getApp().api.queryAppListById(params, {
      success: function (res) {
        wx.hideLoading()
        let result = res.data
        that.setData({
          appList: result
        })
      },
      fail: function (err) {
        wx.hideLoading()
      }
    });
  },


  loadMore() {
    if (this.data.noMoreData || this.data.isRefreshing) return;
    this.setData({
      page: this.data.page + 1
    })
    this.getDeviceOperationLogList();
  },

  refresh() {
    this.setData({
      isRefreshing: true,
      noMoreData: false,
      page: 1
    });
    this.getDeviceOperationLogList(true);
  },

  selectMenu: function (e) {
    let type = e.currentTarget.dataset.type
    let title = e.currentTarget.dataset.title
    let that = this
    let {
      detailInfo
    } = this.data
    if (type == 1) {
      if (detailInfo.deviceStatus == 0 || detailInfo.deviceStatus == -1) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showPayDialog: true
        })
      }

    } else if (type == 2) {
      this.setData({
        type,
        showDialog: false,
        showEditDialog: true
      })
    } else if (type == 3) {
      this.setData({
        type,
        operaTitle: title,
        showDialog: false,
        showOperaDialog: true
      })
    } else if (type == 8) {
      this.queryMdmMerchantStoreList(true)
      this.setData({
        type,
        shopPage: 1,
        showDialog: false,
        showShopDialog: true
      })
    } else if (type == 9) {
      this.queryEnterpriseMerchantUserByAssignList(true)
      this.setData({
        type,
        enterpPage: 1,
        showDialog: false,
        showEnterpriseDialog: true
      })
    } else if (type == 11) {
      this.getMerchantUser();
      this.setData({
        type,
        operaTitle: title,
        showDialog: false,
      })
    } else if (type == 12 && (detailInfo.deviceStatus == 1 || detailInfo.deviceStatus == 4)) {
      this.setData({
        type,
        showDialog: false,
        showAppDialog: true,
      })
    } else if (type == 13) {
      wx.navigateTo({
        url: '/pages/deviceLocationRecord/deviceLocationRecord?id=' + this.data.id,
      })
    } else {
      if (type == 4 && this.data.activationLockStatus == 1) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showOperaDialog: true
        })
      } else if (type == 5) {
        this.getMyDeviceByIdCallback({
          finish: () => {
            if (that.data.detailInfo.deviceStatus > 0 && that.data.detailInfo.deviceStatus != 3) {
              that.setData({
                type,
                showDialog: false,
                showLoseDialog: true
              })
            }
          }
        })
      } else if (type == 10) {
        this.getMyDeviceByIdCallback({
          finish: () => {
            if (that.data.detailInfo.deviceStatus > 0 && (that.data.detailInfo.deviceStatus == 3 || that.data.detailInfo.deviceStatus == 4)) {
              that.setData({
                type,
                operaTitle: title,
                showDialog: false,
                showOperaDialog: true
              })
            }
          }
        })
      } else if (type == 6 && (detailInfo.deviceStatus > 0)) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showOperaDialog: true
        })
      } else if (type == 7 && (detailInfo.deviceStatus > 0)) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showOperaDialog: true
        })
      } else if (type == 14 && (detailInfo.abmStatus == 0)) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showOperaDialog: true
        })
      } else if (type == 8 || type == 9) {
        this.setData({
          type,
          operaTitle: title,
          showDialog: false,
          showOperaDialog: true
        })
      }
    }
  },

  /**
   * 重新下发配置
   */
  sendDefaultRestrict: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在下发配置',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.sendDefaultRestrict(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '下发配置成功',
          icon: 'none'
        })
        that.getDeviceConfig()
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '下发配置失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },


  /**
   * 取消有提示的操作
   */
  cancelOpera: function () {
    this.setData({
      showOperaDialog: false,
      showEditDialog: false,
      showLoseDialog: false,
      showPayDialog: false,
      showCodeDialog: false,
      showAppDialog: false,
      showSceondPasswordDialog: false
    })
  },

  copyCode: function () {
    wx.setClipboardData({
      data: this.data.code,
      success: function (e) {
        wx.showToast({
          title: '复制激活码成功',
          icon: 'none'
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '复制激活码失败' + err,
          icon: 'none'
        })
      }
    })
  },


  confirmOpera: function () {
    const {
      type
    } = this.data
    console.log(type)
    switch (type) {
      case "3": //设备解锁
        //this.deviceUnLock('')
        this.getMerchantUser()
        break;
      case "4": //解除激活锁
        this.closeActivationLock()
        break;
      case "5": //丢失模式
        this.deviceSetLose()
        break;
      case "6": //清除密码
        this.setClearPasscode()
        break;
      case "7": //恢复出厂设置
        this.eraseDevice()
        break;
      case "10": //恢复监管
        this.renewRegulation()
        break;
      case "14": //ABM解绑
        this.disownDevice()
        break
    }
  },



  /**
   * 解除激活锁
   */
  closeActivationLock: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在解除中',
    })
    let params = {
      id: id,
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    console.log(params)
    getApp().api.closeActivationLock(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '解除成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '解除失败' + err.message,
          duration: 3000,
          icon: 'none'
        })

      }
    });
  },
  /**
   * 开启激活锁
   */
  enabledActivationLock: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在开启中',
    })
    let params = {
      id: id,
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.enabledActivationLock(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '开启成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '开启失败' + err.message,
          duration: 3000,
          icon: 'none'
        })

      }
    });
  },


  /**
   * 开启丢失模式
   */
  deviceSetLose: function () {
    let {
      id,
      lostPhone,
      lostContent
    } = this.data
    let that = this

    if (lostPhone == '') {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return
    }
    // if (lostPhone != '') {
    //   const phoneRegExp = /^1[3-9]\d{9}$/;
    //   if (!phoneRegExp.test(lostPhone)) {
    //     wx.showToast({
    //       title: '请输入正确的手机号',
    //       icon: 'none'
    //     })
    //     return
    //   }
    // }
    wx.showLoading({
      title: '正在设置丢失模式',
    })
    let params = {
      id: id,
      losePhone: lostPhone,
      loseContent: lostContent
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.deviceSetLose(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '设置成功',
          icon: 'none'
        })
        setTimeout(() => {
          that.getMyDeviceById()
        }, 50000)

        that.setData({
          showLoseDialog: false,
          lostPhone: '',
          lostContent: ''
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '设置失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
        that.setData({
          showLoseDialog: false
        })
      }
    });
  },
  getMerchantUser: function () {
    let params = {}
    var that = this
    wx.showLoading({
      title: '请稍等...',
    })
    let {
      type
    } = this.data
    getApp().api.getMerchantUser(params, {
      success: function (res) {
        wx.hideLoading()
        if (res.data.merchantId) {
          that.getMerchantInfo(res.data.merchantId)
        } else {
          if (type == 3) {
            that.deviceUnLock('')
          } else {
            that.getEscrowKey('')
          }
        }
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '操作失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },

  getMerchantInfo: function (id) {
    var that = this
    let params = {
      id
    }
    let {
      type
    } = this.data
    getApp().api.getMerchantInfo(params, {
      success: function (res) {
        wx.hideLoading()
        if (type == 3) {
          if (res.data.operatePasswordState == 0) {
            that.deviceUnLock('')
          } else {
            that.setData({
              showOperaDialog: false,
              secondPassword: '',
              showSceondPasswordDialog: true
            })
          }
        } else {
          if (res.data.operatePasswordState == 0) {
            that.getEscrowKey('')
          } else {
            that.setData({
              secondPassword: '',
              showSceondPasswordDialog: true
            })
          }
        }

      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '操作失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },


  /**
   * 获取激活码
   */
  getEscrowKey: function (operatePasswordString) {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在获取激活码',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    if (operatePasswordString) {
      params.operatePasswordString = operatePasswordString
    }
    getApp().api.getEscrowKey(params, {
      success: function (res) {
        wx.hideLoading()
        that.setData({
          code: res.data.escrowKey,
          showCodeDialog: true
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '正在获取激活码失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },



  /**
   * 恢复监管
   */
  renewRegulation: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在恢复监管',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.renewRegulation(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '恢复监管成功',
          icon: 'none'
        })

        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '恢复监管失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },

  /**
   * 设备解锁
   */
  deviceUnLock: function (operatePasswordString) {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在解锁',
    })
    let params = {
      id: id
    }
    if (operatePasswordString) {
      params.operatePasswordString = operatePasswordString
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.deviceUnLock(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '解锁成功',
          icon: 'none'
        })

        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '解锁失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },


  /**
   * 恢复出厂设置
   */
  eraseDevice: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在恢复出厂设置',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.eraseDevice(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '恢复出厂设置成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '恢复出厂设置失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },


  /**
   * ABM解绑
   */
  disownDevice: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在解绑ABM',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.disownDevice(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '解绑ABM成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '解绑ABM失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },
  /**
   * 清楚屏幕密码
   */
  setClearPasscode: function () {
    let {
      id
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在清除中',
    })
    let params = {
      id: id
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.setClearPasscode(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '清除成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '清除失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },

  pickerChange(e) { // 下拉选择器
    console.log('开关选择器：', e.detail.value)
    this.setData({
      newEditState: e.detail.value
    })
  },

  pickerPurDateChange(e) {
    this.setData({
      newPurchaseTime: e.detail.value
    })
  },

  pickerWarrDateChange(e) {
    this.setData({
      newWarrantyTime: e.detail.value
    })
  },

  pickerIndentChange(e) { // 下拉选择器
    console.log('开关选择器：', e.detail.value)
    let that = this
    let {
      rentIdentifierOptions
    } = this.data
    this.setData({
      rentIdentifierVaule: e.detail.value
    })
    that.queryAppListById(rentIdentifierOptions[e.detail.value].value)
  },


  confirmLose: function () {
    this.deviceSetLose();
    this.setData({
      showLoseDialog: false
    })
  },


  /**
   * 获取门店列表
   */
  queryMdmMerchantStoreList: function (refresh = false) {
    var that = this;
    if (this.data.isLoadingShop) return;

    this.setData({
      isLoadingShop: true
    });
    const {
      shopPage,
      shopPageSize
    } = this.data;
    if (!refresh) {
      wx.showLoading({
        title: '加载中',
      })
    }
    let params = {
      page: shopPage,
      limit: shopPageSize
    }
    getApp().api.queryMdmMerchantStoreList(params, {
      success: function (res) {
        console.log(res.data.rows)
        if (res.data.rows) {
          let shopItems = res.data.rows
          shopItems = refresh ? shopItems : that.data.shopItems.concat(shopItems),
            shopItems.forEach(e => {
              e.check = false
            })
          that.setData({
            shopItems: shopItems,
            noMoreDataShop: res.data.total > shopItems.length ? false : true,
            isRefreshingShop: false,
            isLoadingShop: false
          })
          wx.hideLoading()
        }
      },
      fail: function (err) {
        that.setData({
          isLoadingShop: false
        });
        wx.hideLoading()
      }
    });
  },

  loadMoreShop() {
    if (this.data.noMoreDataShop || this.data.isRefreshingShop) return;
    this.setData({
      page: this.data.shopPage + 1
    })
    this.queryMyMdmMerchantStoreList();
  },

  refreshShop() {
    this.setData({
      isRefreshingShop: true,
      noMoreDataShop: false,
      shopPage: 1
    });
    this.queryMyMdmMerchantStoreList(true);
  },


  /**
   * 选择门店
   * @param {*} e 
   */
  checkShop: function (e) {
    let index = e.currentTarget.dataset.index
    let {
      shopItems,
      selectShop
    } = this.data
    shopItems.forEach((e, i) => {
      if (i == index) {
        if (e.check) {
          e.check = false
          selectShop = null
        } else {
          e.check = true
          selectShop = e
        }
      } else {
        e.check = false
      }
    })
    this.setData({
      selectShop,
      shopItems
    })
  },


  /**
   * 分配门店
   */
  confirmShopDialog: function () {
    let {
      selectShop,
      shopItems
    } = this.data
    let hasCheck = false
    shopItems.forEach(e => {
      if (e.check) {
        hasCheck = true
        selectShop = e
      }
    })
    if (hasCheck) {
      this.setData({
        shopItems,
        currentShop: selectShop
      })
      this.deviceAssignStore()
    }
    this.setData({
      showShopDialog: false
    })
  },
  /**
   * 分配门店
   */
  deviceAssignStore: function () {
    let {
      id,
      selectShop
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在分配中',
    })
    let params = {
      assignStoreMerchantId: selectShop.merchantId,
      deviceList: [id]
    }
    console.log(params)
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.deviceAssignStore(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '分配成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showOperaDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '分配失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },









  /**
   * 获取员工列表
   */
  queryEnterpriseMerchantUserByAssignList: function (refresh = false) {
    var that = this;
    if (this.data.isLoadingEnterp) return;

    this.setData({
      isLoadingEnterp: true
    });
    const {
      enterpPage,
      enterpPageSize
    } = this.data;
    if (!refresh) {
      wx.showLoading({
        title: '加载中',
      })
    }
    let params = {
      page: enterpPage,
      limit: enterpPageSize
    }
    getApp().api.queryEnterpriseMerchantUserByAssignList(params, {
      success: function (res) {
        if (res.data.rows) {
          let enterpItems = res.data.rows
          enterpItems = refresh ? enterpItems : that.data.enterpItems.concat(enterpItems),
            enterpItems.forEach(e => {
              e.check = false
            })
          that.setData({
            enterpItems: enterpItems,
            noMoreDataEnterp: res.data.total > enterpItems.length ? false : true,
            isRefreshingEnterp: false,
            isLoadingEnterp: false
          })
          wx.hideLoading()
        }
      },
      fail: function (err) {
        that.setData({
          isLoadingEnterp: false
        });
        wx.hideLoading()
      }
    });
  },

  loadMoreEnterp() {
    if (this.data.noMoreDataEnterp || this.data.isRefreshingEnterp) return;
    this.setData({
      page: this.data.enterpPage + 1
    })
    this.queryEnterpriseMerchantUserByAssignList();
  },

  refreshEnterp() {
    this.setData({
      isRefreshingEnterp: true,
      noMoreDataEnterp: false,
      enterpPage: 1
    });
    this.queryEnterpriseMerchantUserByAssignList(true);
  },


  /**
   * 选择员工
   * @param {*} e 
   */
  checkEnterp: function (e) {
    let index = e.currentTarget.dataset.index
    let {
      enterpItems,
      selectEnterp
    } = this.data
    enterpItems.forEach((e, i) => {
      if (i == index) {
        e.check = true
        selectEnterp = e
      } else {
        e.check = false
      }
    })
    this.setData({
      selectEnterp,
      enterpItems
    })
  },


  /**
   * 分配员工
   */
  confirmEnterpDialog: function () {
    let {
      enterpItems,
      selectEnterp
    } = this.data
    let hasCheck = false
    enterpItems.forEach(e => {
      if (e.check) {
        hasCheck = true
        selectEnterp = e
      }
    })
    if (hasCheck) {
      this.setData({
        enterpItems,
        currentEnterp: selectEnterp
      })
      this.deviceAssignUid()
    }
    this.setData({
      showShopDialog: false
    })
  },
  /**
   * 分配员工
   */
  deviceAssignUid: function () {
    let {
      id,
      selectEnterp
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在分配中',
    })
    let params = {
      assignUid: selectEnterp.uid,
      deviceList: [id]
    }
    console.log(params)
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    getApp().api.deviceAssignUid(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '分配成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showEnterpriseDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '分配失败' + err.message,
          duration: 3000,
          icon: 'none'
        })

      }
    });
  },

  /**
   * 金额支付
   */
  confirmPay: function () {
    this.payBalance()
    this.setData({
      showPayDialog: false
    })
  },

  /**
   * 金额支付
   */
  payBalance: function () {
    let {
      id,
    } = this.data
    let that = this
    wx.showLoading({
      title: '正在支付中',
    })
    let params = {
      deviceList: [id]
    }
    if (getApp().globalData.MerchantStoreInfo && getApp().globalData.MerchantStoreInfo.merchantId) {
      params.storeMerchantId = getApp().globalData.MerchantStoreInfo.merchantId
    }
    console.log(params)

    getApp().api.payBalance(params, {
      success: function (res) {
        if (res.data.errorMsg == "") {
          wx.hideLoading()
          wx.showToast({
            title: '支付成功',
            icon: 'none'
          })
          that.getMyDeviceById()
          that.setData({
            showPayDialog: false
          })
        } else {
          wx.showToast({
            title: '支付失败' + res.data.errorMsg,
            duration: 3000,
            icon: 'none'
          })
        }

      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '支付失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },

  /**
   * 收租确认
   * @param {*} e 
   */
  confirmRent: function (e) {
    let that = this
    const {
      id,
      rentIdentifierOptions,
      rentIdentifierVaule
    } = this.data

    let rentIdentifierId = rentIdentifierOptions[rentIdentifierVaule].value
    let params = {
      id,
      rentIdentifierId
    }
    console.log(params)

    getApp().api.deviceSetRent(params, {
      success: function (res) {
        wx.hideLoading()
        wx.showToast({
          title: '设置收租模式成功',
          icon: 'none'
        })
        that.getMyDeviceById()
        that.setData({
          showAppDialog: false
        })
      },
      fail: function (err) {
        wx.hideLoading()
        wx.showToast({
          title: '设置收租模式失败' + err.message,
          duration: 3000,
          icon: 'none'
        })
      }
    });
  },

  checkAction: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    const {
      actionList
    } = this.data
    actionList.forEach((v, i) => {
      if (i == index) {
        v.nowValue = !v.nowValue
      }
    })
    this.setData({
      actionList
    })
  },


  confirmSecond: function () {
    let {
      secondPassword,
      type
    } = this.data

    if (!secondPassword) {
      wx.showToast({
        title: '请输入二级密码',
        icon: 'none'
      })
      return
    }
    let enkey = getApp().encrypt.encrypt(secondPassword)
    console.log(enkey)
    if (type == 3) {
      this.deviceUnLock(enkey)
    } else {
      this.getEscrowKey(enkey)
    }
    this.setData({
      showSceondPasswordDialog: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let accountType = getApp().globalData.accountType
    this.setData({
      accountType
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})